package chat

import (
	"context"
	"coze_for_sdk/config"
	"coze_for_sdk/controller"
	"coze_for_sdk/controller/auth"
	"coze_for_sdk/model"
	"time"

	"github.com/coze-dev/coze-go"
	"github.com/gin-gonic/gin"
)

func Cancel(c *gin.Context) {
	conversationId := c.Query("conversation_id")
	chatId := c.Query("chat_id")
	if conversationId == "" || chatId == "" {
		controller.Fail(c, controller.ParamsError, "参数错误")
		return
	}

	userId := c.GetInt("user_id")
	//会话和自己不匹配
	var conversation model.CozeConversation
	conversation, err := conversation.GetConversation(conversationId, userId)
	if err != nil {
		controller.Fail(c, controller.BusinessError, "会话不存在")
		return
	}

	// Get an access_token through personal access token or oauth.
	token := auth.GetCozeAccessToken()
	if token == "" {
		controller.Fail(c, controller.BusinessError, "get access token error")
		return
	}
	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()
	authCli := coze.NewTokenAuth(token)

	// Init the Coze client through the access_token.
	cozeCli := coze.NewCozeAPI(authCli, coze.WithBaseURL(config.DefaultConfig.Coze.ApiBase))

	_, err = cozeCli.Chat.Cancel(ctx, &coze.CancelChatsReq{
		ConversationID: conversationId,
		ChatID:         chatId,
	})
	if err != nil {
		controller.Fail(c, controller.BusinessError, "取消失败")
		return
	}

	controller.Success(c, "取消成功")
}
